<!-- Checkbox.svelte -->
<script lang="ts">
	import { getContext, onDestroy } from 'svelte';
	import CheckSquare from './CheckSquare.svelte';
	import { CHECKBOX_GROUP_CONTEXT_KEY } from './context';
	import type { CheckboxRegistry, CheckboxGroupContext, Variant } from './types';

	// 对外暴露的属性 - 新增border属性控制边框样式
	export let value: any = null;
	export let label: string | number = '';
	export let disabled: boolean = false;
	export let name: string = '';
	export let size: 'sm' | 'md' | 'lg' | null = null;
	export let className: string = '';
	export let variant: Variant = 'primary';
	export let modelValue: any[] | boolean = [];
	export let indeterminate: boolean = false;
	export let onchange: ((value: any[] | boolean) => void) | undefined = undefined;
	export let buttonStyle: boolean = false; // 按钮样式（与边框样式互斥）
	export let border: boolean = false; // 是否启用边框样式
	export let noSquare: boolean = false;

	let checked: boolean = false;
	const group: CheckboxGroupContext | undefined = getContext(CHECKBOX_GROUP_CONTEXT_KEY);

	// 组内注册逻辑
	if (group) {
		const checkbox: CheckboxRegistry = {
			value,
			currentChecked: false,
			updateChecked: (isChecked) => (checked = isChecked)
		};
		const unregister = group.register(checkbox);
		onDestroy(() => unregister && unregister());
	}

	// 单独使用时同步选中状态
	$: if (!group) {
		if (typeof modelValue === 'boolean') {
			checked = modelValue;
		} else {
			checked = modelValue.includes(value);
		}
	}

	// 计算最终属性（依赖组配置或自身属性，优先级：组 > 单个组件）
	const defaultRandomName = () => `checkbox-${Math.random().toString(36).slice(2, 8)}`;
	let finalName: string;
	let finalDisabled: boolean;
	let finalSize: 'sm' | 'md' | 'lg';
	let finalColor: string;
	let isButtonStyle: boolean; // 最终按钮样式状态
	let isBorder: boolean; // 最终边框样式状态（与按钮样式互斥）

	$: {
		finalDisabled = disabled || (group?.disabled ?? false);
		finalSize = size || (group?.size ?? 'md');
		finalColor = variantColors[variant] || 'var(--color-primary-600)';
		finalName = name || (group?.name ?? defaultRandomName());
		isButtonStyle = buttonStyle || (group?.buttonStyle ?? false); // 组优先
		isBorder = !isButtonStyle && (border || (group?.border ?? false)); // 按钮样式优先级高于边框，组优先
	}

	// 变体颜色映射（用于边框和文本颜色）
	const variantColors = {
		info: 'var(--color-info-600)',
		primary: 'var(--color-primary-600)',
		secondary: 'var(--color-secondary-600)',
		success: 'var(--color-success-600)',
		warning: 'var(--color-warning-600)',
		error: 'var(--color-error-600)'
	};

	// 点击处理逻辑
	function handleClick(event: Event) {
		event.stopPropagation();

		if (finalDisabled) return;
		if (group) {
			group.onToggle(value);
		} else {
			let newValue;
			if (typeof modelValue === 'boolean') {
				newValue = !modelValue;
			} else {
				newValue = checked ? modelValue.filter((item) => item !== value) : [...modelValue, value];
			}
			modelValue = newValue;
			onchange?.(newValue);
		}
	}

	function handleKeydown(e: KeyboardEvent) {
		if ((e.key === 'Enter' || e.key === ' ') && !finalDisabled) {
			e.preventDefault();
			handleClick(new MouseEvent('click', { bubbles: true }));
		}
	}
</script>

<div
	class={`checkbox checkbox--${finalSize} ${className}`}
	class:checkbox--button={isButtonStyle}
	class:checkbox--border={isBorder}
	class:checkbox--disabled={finalDisabled}
	class:checkbox--indeterminate={indeterminate}
	style={`
		--checkbox-color: ${finalColor};
		--checkbox-border-color: ${finalDisabled ? 'var(--color-info-300)' : finalColor};
	`}
	onclick={handleClick}
	onkeydown={handleKeydown}
	role="checkbox"
	aria-checked={indeterminate ? 'mixed' : checked}
	aria-disabled={finalDisabled}
	tabindex={finalDisabled ? -1 : 0}
>
	<input
		type="checkbox"
		class="checkbox__input"
		name={finalName}
		{checked}
		disabled={finalDisabled}
		style="display: none;"
	/>

	{#if !isButtonStyle}
		<!-- 复选框图标 -->
		{#if !noSquare}
			<CheckSquare {checked} {indeterminate} size={finalSize} disabled={finalDisabled} />
		{/if}

		<!-- 标签显示 -->
		{#if label}
			<!-- 多个动态class -->
			<span class="checkbox__label {noSquare ? '' : 'noSquareLabel'}">
                {label}
            </span>
		{/if}
	{:else}
		<!-- 按钮样式标签 -->
		<span class="checkbox__button-label">{label}</span>
	{/if}
</div>

<style lang="scss" scoped>
	.checkbox {
		display: inline-flex;
		align-items: center;
		cursor: pointer;
		user-select: none;
		padding: 4px 16px;
	}

	.checkbox--sm {
		height: 26px;
		padding: 0 8px;
	}

	.checkbox--md {
		height: 28px;
		padding: 0 10px;
	}

	.checkbox--lg {
		height: 30px;
		padding: 0 12px;
	}

	// 状态相关基础样式
	.checkbox:has(.checkbox__input:checked),
	.checkbox.checkbox--indeterminate {
		color: var(--checkbox-color);		
	}
	.checkbox--disabled {
		cursor: not-allowed;
		opacity: 0.7;
	}

	// 边框样式核心样式
	.checkbox--border {
		border: 1px solid var(--color-info-300);
		border-radius: 4px;
		transition: all 0.2s ease;
		background: var(--color-page);

		// 选中状态
		&:has(.checkbox__input:checked) {
			border-color: var(--checkbox-color);
		}
		// 半选状态
		&.checkbox--indeterminate {
			border-color: var(--checkbox-color);
		}
	}

	// 按钮样式核心样式
	.checkbox--button {
		border: 1px solid var(--color-info-300);
		border-radius: 4px;
		margin: 0 4px 4px 0;
		transition: all 0.2s ease;

		// 未选中状态
		&:not(.checkbox--disabled):not(:has(.checkbox__input:checked)) {
			&:hover {
				color: var(--checkbox-color);
			}
		}

		// 选中状态
		&:has(.checkbox__input:checked) {
			background-color: var(--checkbox-color);
			color: white;
			border-color: var(--checkbox-color);
			box-shadow: -1px 0 0 0 var(--color-info-300);
		}
	}

	// 按钮样式标签样式
	.checkbox__button-label {
		font-size: 13px;
		line-height: 15px;

		.checkbox--sm & {
			font-size: 12px;
			line-height: 14px;
		}

		.checkbox--lg & {
			font-size: 14px;
			line-height: 16px;
		}
	}

	.checkbox__label {
		font-size: 13px;
		line-height: 15px;

		.checkbox--sm & {
			font-size: 12px;
			line-height: 14px;
		}

		.checkbox--lg & {
			font-size: 14px;
			line-height: 16px;
		}
		&.noSquareLabel{
			margin-left: 8px
		}
	}

	// 组内按钮样式调整
	:global(.checkbox-group--button .checkbox--button) {
		margin: 0;
		border-radius: 0;

		&:first-child {
			border-top-left-radius: 4px;
			border-bottom-left-radius: 4px;
		}

		&:last-child {
			border-top-right-radius: 4px;
			border-bottom-right-radius: 4px;
		}

		&:not(:first-child) {
			border-left: none;
		}
	}
	.squeryMargin{
		margin-right: 8px;
	}
</style>
